﻿using CPPEI.Coolzon.Event.NCL;
using CPPEI.Coolzon.Event.UI;
using CPPEI.Coolzon.Service.Contract;
using CPPEI.Coolzon.ServiceProxy;
using CPPEI.Coolzon.UI.Views.Windows;
using Sunboxsoft.ChanceData.ServiceProxy.MainServiceRef;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace CPPEI.Coolzon.UI.Views
{
    /// <summary>
    /// Interaction logic for SelectSolutionView.xaml
    /// 选择方案视图
    /// </summary>
    public partial class SelectSolutionView : View, Coolvis.UI.Theme.Console.ISelectSolutionView
    {
        private string _preSolutionName;
        public string SelectedSolutionName { get; private set; }

        /// <summary>
        /// 是否是切换方案
        /// </summary>
        private bool _isSwitchSolution;

        /// <summary>
        /// 是否是新建的控制域，在用户点击方案时会向服务器提出创建一个控制域的请求，
        /// 但是如果服务器上已经存在了控制域，那么不会创建信息的，此值为false，
        /// 如果创建了新的控制域，此值为true
        /// </summary>
        public bool IsNewDomain { get; private set; }

        public SelectSolutionView()
        {
            InitializeComponent();
            Common.EventBus.Instance.Register(this);
            Common.EventBus.Create(ClientProxyManager.EVENTBUS_FLAGNAME).Register(this);
            NCLEventBus.Register(this);

            SetFullScreenText();
        }

        public SelectSolutionView(string solutionName)
            : this()
        {
            _preSolutionName = solutionName;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="currentSolutionName"></param>
        /// <param name="isSwitchSolution"></param>
        /// <param name="isCanBeBack"></param>
        public SelectSolutionView(string currentSolutionName, bool isSwitchSolution, bool isCanBeBack=true)
            : this()
        {
            _preSolutionName = currentSolutionName;
            _isSwitchSolution = isSwitchSolution;

            if (isCanBeBack)
            {
                _ctlBtnBack.Visibility = System.Windows.Visibility.Visible;
            }
        }

        #region override

        protected override void OnActive()
        {
            // 构造获取方案列表的请求
            NCLGetSolutionListEvent @event = new NCLGetSolutionListEvent();
            Common.EventBus.Instance.PublishAsync(@event);

            tbAccountName.Text = UIContext.Current.UserAccount;
            base.OnActive();
        }

        protected override void OnDeactive()
        {
            Common.EventBus.Instance.Unregister(this);
            Common.EventBus.Create(ClientProxyManager.EVENTBUS_FLAGNAME).Unregister(this);
            NCLEventBus.Unregister(this);

            base.OnDeactive();
        }

        #endregion

        private void _ctlBtnRetry_Click(object sender, RoutedEventArgs e)
        {
            // 构造获取方案列表的请求
            NCLGetSolutionListEvent @event = new NCLGetSolutionListEvent();
            NCLEventBus.PublishAsync(@event);
        }


        void btnSolution_Click(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;
            SolutionItem solutionItem = (button.Tag as SolutionItem);
            SelectedSolutionName = solutionItem.Name;

            if (_isSwitchSolution)
            {
                // 发送切换方案事件
                CPPEI.Coolzon.Event.NCL.NCLSwitchSolutionEvent @event = new CPPEI.Coolzon.Event.NCL.NCLSwitchSolutionEvent(SelectedSolutionName);
                CPPEI.Coolzon.Event.NCL.NCLEventBus.Publish(@event);
                this.Cancel();
            }
            else
            {
                if (!UIContext.Current.IsAutoCreateDomain)
                {

                    SelectDomainWindows selectDomain = new SelectDomainWindows(button.Tag as SolutionItem);
                    selectDomain.Title = solutionItem.Caption;

                    if (selectDomain.ShowDialog().Value)
                    {
                        this.Submit();
                    }
                }
                else
                {
                    // 构造创建控制域的请求
                    Service.Contract.ReqCreateDomainData requestData = new Service.Contract.ReqCreateDomainData();
                    requestData.SolutionCaption = solutionItem.Caption;
                    requestData.SolutionName = solutionItem.Name;
                    requestData.DomainCaption = "Auto";

                    Request request = RequestUtil.BuildRequest(
                        UIContext.Current.ControlDomainId,
                        UIContext.Current.UserIdentity,
                        Service.Contract.REQUEST_SCENARIO.CONNENT,
                        Service.Contract.REQUEST_COMMAND.CONNECT.CREATEDOMAIN,
                        Service.Contract.REQUEST_MODE.SELF,
                        requestData);
                    ClientProxyManager.Instance.SendRequestSys(request);
                }
            }
        }

        [Common.Subscribe]
        public void OnReceiveCreateDomainData(Service.Contract.RespCreateDomainData data)
        {
            if (data != null && data.IsSuccess)
            {
                UIContext.Current.ControlDomainId = data.DomainId;
                UIContext.Current.OperatorIdentity = data.OperatorIdentity;
                this.IsNewDomain = data.IsNewDomain;

                this.Dispatcher.Invoke(() =>
                {
                    Common.EventBus.Create(ServiceProxy.ClientProxyManager.EVENTBUS_FLAGNAME).Unregister(this);
                    this.Submit();
                });
            }
            else if (data != null)
            {
                MessageBox.Show(data.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            else
            {
                MessageBox.Show("未知错误!", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void Logout_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            LogoutView logoutView = new LogoutView();
            UIContext.Current.RootViewContainer.PopView("注销", logoutView);
        }

        /// <summary>
        /// 收到来自服务器的注销结果
        /// </summary>
        /// <param name="event"></param>
        [CPPEI.Coolzon.Common.Subscribe]
        public void OnReceiveLogoutEvent(Service.Contract.RespLogoutData @event)
        {
            this.Dispatcher.Invoke(() =>
            {
                Common.EventBus.Create(ServiceProxy.ClientProxyManager.EVENTBUS_FLAGNAME).Unregister(this);
                this.Cancel();
            });
        }

        /// <summary>
        /// 全屏或是退出全屏
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tbFullscreen_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            UIEventBus.Publish(new UIChangeFullScreenStateEvent());
            if (UIContext.Current.IsFullScreen)
            {
                tbFullscreen.Text = "还原";
            }
            else
            {
                tbFullscreen.Text = "全屏";
            }
        }

        /// <summary>
        /// 设置文本为全屏或还原
        /// </summary>
        private void SetFullScreenText()
        {
            if (UIContext.Current.IsFullScreen)
            {
                tbFullscreen.Text = "还原";
            }
            else
            {
                tbFullscreen.Text = "全屏";
            }
        }

        private void _ctlBtnBack_Click_1(object sender, RoutedEventArgs e)
        {
            UIEventBus.Publish(new UIHideSwitchSolutionViewEvent());
        }
    }
}
